﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace Prototipo.CMS.Models
{
    public class Post
    {
        [Required(ErrorMessage = "Você deve informar o título do post")]
        public string Title { get; set; }

        [Required(ErrorMessage = "Você deve inserir um conteudo do post")]
        public string Content { get; set; }

        public string Tags { get; set; }

        public static IEnumerable<Post> GetAll(string xmlPath)
        {
            var xml = XDocument.Load(xmlPath);
            return xml.Root.Elements().Select(xElement => new Post
            {
                Title = xElement.Element("Title").Value, 
                Content = xElement.Element("Content").Value, 
                Tags = xElement.Element("Tags").Value
            }).ToList();
        }

        public static void Save(string xmlPath, Post post)
        {
            var xml = XDocument.Load(xmlPath);
            var p = xml.Root.Elements().Where(x => x.Element("Title").Value == post.Title).FirstOrDefault();
            if (p == null)
            {
                xml.Root.Add(new XElement("Post",
                    new XElement("Title", post.Title),
                    new XElement("Content", new XCData(post.Content)),
                    new XElement("Tags", post.Tags)
                        ));
            }
            else
            {
                p.Element("Title").Value = post.Title;
                p.Element("Content").Value = post.Content;
                p.Element("Tags").Value = post.Tags;
            }

            xml.Save(xmlPath);
        }

    }
}